<template>
  <div class="app-login">
    <el-form ref="formRef" :model="model" :rules="rules" label-width="100">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="model.username" />
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input v-model="model.password" type="password" />
      </el-form-item>

      <el-form-item label="验证码" prop="verifyCode">
        <el-space>
          <el-input v-model="model.verifyCode" @keyup.enter="handleLogin" />
          <Captcha ref="captchaRef" v-model="model.captchaId" />
        </el-space>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" :loading="loading" @click="handleLogin"> Login</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import Captcha from '@/pages/login/components/captcha.vue'
import { reactive, ref } from 'vue'
import { type FormInstance, type FormRules } from 'element-plus'
import { baseOpenLogin } from '@/api'
import { useUserStore } from '@/stores/user'
import router from '@/router'

const user = useUserStore()

// 表单校验规则
const rules: FormRules = {
  username: [{ required: true, message: 'Username 必须' }],
  password: [{ required: true, message: 'Password 必须' }],
  verifyCode: [{ required: true, message: 'VerifyCode 必须', trigger: 'blur' }]
}
// 表单数据对象
const model = reactive({
  username: 'admin',
  password: '123456',
  captchaId: '', // 验证码id
  verifyCode: ''
})
const loading = ref(false)
const formRef = ref<FormInstance>()
const captchaRef = ref<InstanceType<typeof Captcha>>()

// 登录
async function handleLogin() {
  // 表单校验
  await formRef.value?.validate()

  loading.value = true

  try {
    // 登录接口调用
    await baseOpenLogin(model).then(user.setToken)

    // 跳转首页
    await router.push('/')
  } catch (err: any) {
    // 刷新验证码
    captchaRef.value?.refresh()

    // 清空验证码输入框
    model.verifyCode = ''
  }

  loading.value = false
}
</script>

<style scoped>
.app-login {
  height: 100%;
  overflow: hidden;
  background-color: #f2f2f2;
}

.el-form {
  margin: 50px auto;
  padding: 16px;
  width: 360px;
  border-radius: 10px;
  background-color: #fff;
}
</style>
